
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";

export default async function (ctx: FunctionContext) {
  let body = ctx.body
  /**
   * {
   *     "activityId": "656204a6b5171888d9700bfb",
   *     "activityRuleList": [
   *         {
   *             "activityId": "656204a6b5171888d9700bfb",
   *             "conditionAmount": "",
   *             "conditionNum": "1",
   *             "benefitAmount": "",
   *             "benefitDiscount": "50"
   *         }
   *     ],
   *     "activitySkuList": [
   *         {
   *             "skuId": "6562c1b9b5171888d9700c38"
   *         }
   *     ],
   *     "couponIdList": []
   * }
   */
  if (nw.util.isNull(body.activityId)){
    return fail("数据不合法")
  }
  let activityInfo  = await nw.db.findById({
    dbName:"activityInfo",
    id:body.activityId
  })
  if (nw.util.isNull(activityInfo)){
    return fail("活动不存在")
  }
  //1.清楚就数据
  const p1 = nw.db.del({
    dbName:"activityRule",
    whereJson:{activityId:activityInfo._id}
  })
  const p2 = nw.db.del({
    dbName:"activitySku",
    whereJson:{activityId:activityInfo._id}
  })

  await Promise.all([p1,p2])

  //2.保存活动规则
  let activityRuleList = body.activityRuleList
  if (!nw.util.isNull(activityRuleList)&&nw.util.isArray(activityRuleList)&&activityRuleList.length>0){
    let activityRules = []
    for (let i = 0; i < activityRuleList.length; i++) {
      let each = activityRuleList[i]
      let rule = {
        activityId:body.activityId,
        activityType:activityInfo.activityType,
        conditionAmount:each.conditionAmount,
        conditionNum:each.conditionNum,
        benefitAmount:each.benefitAmount,
        benefitDiscount:each.benefitDiscount,
        createTime:new Date(),
        updateTime:new Date(),
        deleted:0
      }
      activityRules.push(rule)
    }
    //保存即可
    await cloud.database().collection("activityRule").add(activityRules,{multi:true})
  }

  //3.保存活动参与商品activitySku
  let activitySkuList = body.activitySkuList
  if (!nw.util.isNull(activitySkuList)&&nw.util.isArray(activitySkuList)&&activitySkuList.length>0){
    let activitySkus = []
    for (let i = 0; i < activitySkuList.length; i++) {
      let each = activitySkuList[i]
      let activitySku = {
        activityId:activityInfo._id,
        skuId:each.skuId,
        createTime:new Date(),
        updateTime:new Date(),
        deleted:0
      }
      activitySkus.push(activitySku)
    }
    await cloud.database().collection("activitySku").add(activitySkus,{multi:true})
  }
  return ok("保存成功")
}
